package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.vo.CommMemberVo;
import com.atguigu.eduservice.client.UcenterClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.servicebase.exceptionhandler.SelfExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *课程评论
 * @author testjava
 * @since 2023-04-27
 */
@RestController
@RequestMapping("/eduservice/educomment")
@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    //远程调用
    @Autowired
    private UcenterClient ucenterClient;

    /**
     * 分页查询评论
     * @param current
     * @param limit
     * @return
     */
    @PostMapping("/pageComment/{current}/{limit}")
    public R pageComment(@PathVariable long current,@PathVariable long limit,String courseId)
    {
       Map<String,Object> map=commentService.pageList(current,limit,courseId);
       return R.ok().data(map);
    }

    /**
     * 新增一条评论
     * 获取用户信息，根据token
     * 远程调用ucenter
     * @param comment
     * @param request
     * @return
     */
    @PostMapping("/insertComment")
    public R insertComment(@RequestBody EduComment comment, HttpServletRequest request){
        System.out.println(comment);
        //获取用户信息
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        //判空未登录
        if(StringUtils.isEmpty(memberIdByJwtToken))
        {
            System.out.println("未登录");
            return R.error().data("msg","还未登录请先登录");
        }
        //根据id查询用户信息，远程调用
        CommMemberVo commMemberInfo = ucenterClient.getCommMemberInfo(memberIdByJwtToken);
        if(comment!=null)
        {
            //用户信息
            comment.setMemberId(commMemberInfo.getId());
            comment.setAvatar(commMemberInfo.getAvatar());
            comment.setNickname(commMemberInfo.getNickname());
            comment.setIsDeleted(0);//初始化都是不删除的
        }
        else{
            return R.error();
        }


        boolean save = commentService.save(comment);
        if(save)
        {
            return R.ok().data("msg","添加成功");

        }

        throw  new SelfExceptionHandler("添加失败",20001);
    }
}

